package com.luoguijia.disk.login.control;

import com.luoguijia.disk.login.entity.UserEntity;
import com.luoguijia.disk.login.service.LoginService;
import com.luoguijia.disk.spring.control.BaseController;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginControl extends BaseController {
    @Resource
    private HttpSession httpSession;
    @Resource
    private LoginService loginService;

    // 原有：登录失败处理页
    @RequestMapping("/loginError")
    public String loginError(HttpSession session, Model model) {
        // 新增：累计错误次数
        Integer errorCount = (Integer) session.getAttribute("errorCount");
        errorCount = errorCount == null ? 1 : errorCount + 1;
        session.setAttribute("errorCount", errorCount);

        // 新增：错误次数≥3时标记需要验证码
        if (errorCount >= 3) {
            session.setAttribute("needVerify", true);
        }else{
            session.setAttribute("needVerify", false);
        }

        // 新增：传递错误提示
        model.addAttribute("errorMsg", "用户名或密码错误");

        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());
        return "redirect:/login/login";
    }

    // 原有：登录验证逻辑（修复 needVerify 清除逻辑）
    @PostMapping("/verification")
    public String verification(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam(required = false) String verifyCode, // 前端传的验证码
            HttpSession session,
            Model model
    ) {
        // 1. 获取错误次数（原逻辑保留）
        Integer errorCount = (Integer) session.getAttribute("errorCount");
        errorCount = errorCount == null ? 0 : errorCount;

        // 2. 校验密码（原逻辑保留，但调整后续流程）
        if (!loginService.verifyLogin(username, password)) {
            errorCount++;
            session.setAttribute("errorCount", errorCount);

            // 原逻辑：错误次数≥3时标记需要验证码
            if (errorCount >= 3) {
                session.setAttribute("needVerify", true);
            }

            model.addAttribute("errorMsg", "用户名或密码错误");
            return "login/loginPage";
        }

        // 3. 到这里，说明密码校验成功，但如果错误次数≥3，还需要校验验证码
        if (errorCount >= 3) {
            // 从 session 取存储的验证码和过期时间
            String sessionCode = (String) session.getAttribute("SESSION_VERIFY_CODE");
            Long expireTime = (Long) session.getAttribute("SESSION_VERIFY_CODE_EXPIRE");

            // 校验验证码是否过期、是否正确
            if (sessionCode == null || expireTime == null || expireTime < System.currentTimeMillis()) {
                model.addAttribute("errorMsg", "验证码已过期，请重新获取");
                return "login/loginPage";
            }
            if (!sessionCode.equals(verifyCode)) {
                model.addAttribute("errorMsg", "验证码错误");
                return "login/loginPage";
            }
        }

        // 4. 登录成功，清除所有验证码、错误次数相关标记（原逻辑保留）
        session.removeAttribute("errorCount");
        session.removeAttribute("needVerify");
        session.removeAttribute("SESSION_VERIFY_CODE");
        session.removeAttribute("SESSION_VERIFY_CODE_EXPIRE");

        return "redirect:/main";
    }

    // 原有：登录页面跳转
    @RequestMapping("/login")
    public String loginPage() {
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());
        return "login/loginPage";
    }

    // 原有：注册页面跳转
    @RequestMapping("/register")
    public String registerPage() {
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());
        return "login/registerPage";
    }

    // 原有：主页面跳转
    @RequestMapping("/main")
    public String mainPage() {
        return "redirect:/";
    }

    // 原有：发送手机验证码
    @PostMapping("/sendVerificationCode")
    @ResponseBody
    public String sendVerificationCode(@RequestParam String phone) {
        return loginService.sendVerificationCode(phone);
    }

    // 原有：用户注册
    @PostMapping("/register")
    public String registerUser(@ModelAttribute("userEntity") UserEntity user, @RequestParam String verificationCode, Model model) {
        System.out.println("开始注册用户: " + user.getUsername());
        boolean result = loginService.registerUser(user, verificationCode);
        System.out.println("注册结果: " + result);
        if (result) {
            model.addAttribute("message", "注册成功，请登录");
            System.out.println("注册成功，重定向到登录页面");
            return "redirect:/login/login";
        } else {
            model.addAttribute("errorMessage", "注册失败，可能原因：验证码错误或手机号已注册");
            System.out.println("注册失败，返回注册页面");
            return "login/registerPage";
        }
    }

    // 原有：获取验证码图片
    @RequestMapping("/getVerifyImag")
    public ResponseEntity<byte[]> getVerifyImag(String rand) {
        return loginService.getVerifyImag();
    }
    @RequestMapping("/verifyCode")
    @ResponseBody
    public String verifyCode(
            @RequestParam("userInputCode") String userInputCode // 接收用户输入的验证码
    ) {
        System.out.println("进入 verify 方法"); // 添加日志，确认方法是否被调用
        // 1. 从 session 获取存储的验证码和过期时间
        String storedCode = (String) httpSession.getAttribute("SESSION_VERIFY_CODE");
        Long expireTime = (Long) httpSession.getAttribute("SESSION_VERIFY_CODE_EXPIRE");

        // 2. 验证码校验逻辑
        if (storedCode == null) {
            return failJson("login.verify.auth.fail");
        }
        if (expireTime != null && System.currentTimeMillis() > expireTime) {
            return  failJson("login.verify.auth.fail");
        }
        if (userInputCode == null || !userInputCode.toUpperCase().equals(storedCode.toUpperCase())) {
            return failJson("login.verify.auth.fail");
        }

        // 3. 校验通过，返回业务数据
        return successJson("login.verify.auth.success");
    }
}